var dkFee = 0;  			//积分抵扣费用
var jfdkbl;     			//积分抵扣比例
var crusrPoints;            //用户拥有的积分数

//购买的单个商品数量加
function add(obj) {
	var jc_select = $(obj);
	
	//商品数量
	var goodCount = jc_select.parent().find('.span_count_flag');
	var goodCountN = parseInt(goodCount.text())+1;
	goodCount.html(goodCountN);
	
	//单价
	var priceHtml = jc_select.parent().parent().find('.div_storeInfo_price');
	var price = parseFloat(priceHtml.html().substring(1));
		
	//每样商品的小计
	var countPrice =  (price*goodCountN).toFixed(2);
	
	//可获得积分
	var khdScore = jc_select.parent().parent().find('.div_count').find('.span_count_flag');     //alert(khdScore+'---------'+khdScore.split("：")[1]);
	//商品数量大于1
	var khdScoreCount;var score = "";
	if(goodCountN-1 >1){
		score = ((khdScore.html().split(":")[1]) / (goodCountN - 1));
	}else{
		score = (khdScore.html().split(":")[1]);
	}
	khdScoreCount = score * goodCountN;
	khdScore.html(countPrice+"元，可获得积分:"+khdScoreCount);
	var hdScoreZN = parseInt($("#hdScoreZ").text()) + parseInt(score);
	var countPriceN = parseFloat($("#total_number").html()) + price - dkFee;
	yzf(hdScoreZN,countPriceN,dkFee);
}
//购买的单个商品数量减
function subtract(obj) { 
	var jc_select = $(obj); 
	
	//商品数量
	var goodCount = jc_select.parent().find('.span_count_flag');
	var goodC = parseInt(goodCount.text());
	if(goodC == 1){
		return;
	}
	var goodCountN = parseInt(goodCount.text())-1;
	goodCount.html(goodCountN);
	
	//单价
	var priceHtml = jc_select.parent().parent().find('.div_storeInfo_price');
	var price = parseFloat(priceHtml.html().substring(1));
	
	//每样商品的金额小计
	var countPrice =  (price*goodCountN).toFixed(2);
	
	//可获得积分
	var khdScore = jc_select.parent().parent().find('.div_count').find('.span_count_flag');
	//商品数量大于1
	var khdScoreCount;var score = "";
	if(goodCountN+1 > 1){
		score = ((khdScore.html().split(":")[1]) / (goodCountN + 1));
	}else{
		score = (khdScore.html().split(":")[1]);
	}
	khdScoreCount = score * goodCountN;
	khdScore.html(countPrice+"元，可获得积分:"+khdScoreCount);
	
	var hdScoreZN = parseInt($("#hdScoreZ").text()) - parseInt(score);
	var countPriceN = parseFloat($("#total_number").html()) - price - dkFee;
	yzf(hdScoreZN,countPriceN,dkFee);
}
//新增的积分数，每样商品金额小计，抵扣费用
function yzf(hdScoreZN,countPriceN,dkFee){
	//可获得总积分	
	$("#hdScoreZ").html(hdScoreZN);
	
	//应支付
	$("#total_number").html(countPriceN.toFixed(2));
}

//去支付
function sure_pay() {
    var selectedAddress = JdataGet('selectedAddress');
    if(!selectedAddress) {
        alert("请先输入你的收货地址！");
        return;
    }
    var r = confirm("确定购买此商品");
    if (r==false) {
        return;
    }

    layer.open({type: 2});
    sureToPay();
}

//添加新地址
function addNewAddress() {
    nextView("../store/addressManage.html");  
}

//初始化
function init(){
	var userUuid = dataGet("userUuid");
	viewsScore(userUuid);
	
	var data= "userId=" + userUuid;
    var url = urlfile + "coreShoppingCart/userCartView";
    ajaxTool("post",data,url,
        function error(XMLHttpRequest, textStatus, errorThrown,fnErr){
            alert("error:" + XMLHttpRequest);
        },
        function success(data){
            if(!data.success) {
                alert(data.errMsg);
            }else{
            	if(data.data && data.data.length>0){
	            	var item = "";var kkdzjf = 0;
	            	for(var i=0; i<data.data.length; i++) {
	            	    var info = urlfile + 'coreAttachment/image/get/' +  data.data[i].criglGoodsImg;
	            		item +='<div class="div_storeInfo">'+
			            			'<div class="img_store_pic" style="background:url('+ info +') no-repeat;-webkit-background-size: 88px 78px;background-size: 88px 78px;font-size:12px">'+data.data[i].criglGoodsName+'</div>'+
			            			'<div class="div_storeInfo_detail">'+
				    				    '<div id="title"></div>'+
				    				    '<div class="div_storeInfo_price" data-price="0">￥'+data.data[i].criglGoodsPrice+'</div>'+
				    				    '<div class="count_number">'+
				    					   '<div class="div_add_subtract btn" onclick="subtract(this)">-</div>'+
				    					   '<span class="span_count_flag div_storeInfo_number" style="margin-left: 18px;" >'+data.data[i].criglGoodsAmount+'</span>'+
				    					   '<div class="div_add_subtract btn" onclick="add(this)">+</div>'+
				    				    '</div>'+
				    				    '<div class="div_count">'+
				    					   '<span class="span_count_flag">可获得积分:'+data.data[i].criglGoodsScore+'</span>'+
				    				    '</div>'+
				    				'</div>'+
				    		   '</div>';
	            		
	            		//初始化时计算金额和积分 
	            	    kkdzjf = kkdzjf + data.data[i].criglGoodsScore;
	            		$("#hdScoreZ").html(kkdzjf);
	            		
	            		//应支付
	            		var price = parseFloat(data.data[i].criglGoodsPrice);
	            		var goodCountN = parseInt(data.data[i].criglGoodsAmount);
	            		
	            		var countPrice =  price * goodCountN;  //alert(countPrice + "------------" +parseFloat($("#total_number").html()));
	            		var countPriceN = parseFloat($("#total_number").html()) + countPrice - dkFee;
	            		$("#total_number").html(countPriceN.toFixed(2));	            		
	            	}
	            	$('#data-item').html(item);
            	}
            }
    });
    
	var data= "&crarsUser=" + userUuid;
    var url = urlfile + "coreAddress/find/my/address";
    ajaxTool("post",data,url,
        function error(XMLHttpRequest, textStatus, errorThrown,fnErr){
            alert("error:" + XMLHttpRequest);
        },
        function success(data){
            if(!data.success) {
                alert(data.errMsg);
            }else{
            	if(data.data && data.data.length>0){
            		var select = dataGet("addressIndex");
            		if(select==null || select>data.data.length){
            			select=0;
            		}
            		JdataSave('selectedAddress',data.data[select]);
            		$('#name').html("收货人："+ data.data[select].crarsName);
                    crporName = data.data[select].crarsName;
            		$('#phoneNo').html(data.data[select].crarsTel);
                    crporTel = data.data[select].crarsTel;
            		$('#address').html("收货地址："+data.data[select].crarsCity+data.data[select].crarsAddress);
                    crporCity = data.data[select].crarsCity;
                    crporAddress = data.data[select].crarsAddress;
            	}else{
					$("#pay_address").html('<span style="color: #b4b4b4;line-height: 97px;">您还没有收货地址，</span><span style="color: #ffae00;">请添加地址</span>');
            	}
            }
        }
    );
}

function initScore(){
	var jc_item = $('.div_storeInfo');
    var goodsInfo = '';var countpriceN = 0;
	for (var i = 0; i < jc_item.length; i++) {  //循环每一商品
		var item = jc_item.eq(i);
		var item_goodName = item.find('.img_store_pic').html();
		var item_goodPrice = item.find('.div_storeInfo_detail').find('.div_storeInfo_price').html();
		var item_goodCount = item.find('.div_storeInfo_detail').find('.count_number').find('.span_count_flag,.div_storeInfo_number').html();
		var item_goodScore = item.find('.div_storeInfo_detail').find('.div_count').find('.span_count_flag').html();
		
		if(goodsInfo==''){
			goodsInfo = item_goodName+'~'+item_goodPrice+'~'+item_goodCount+'~'+item_goodScore.split(":")[1];
		}else{
			goodsInfo = goodsInfo +"#"+item_goodName+'~'+item_goodPrice+'~'+item_goodCount+'~'+item_goodScore.split(":")[1];
		}
		
		//应支付
		var price = parseFloat(s.html().substring(1));
		var goodCountN = parseInt(goodCount.text());
		
		var countPrice =  price * goodCountN;  alert("countprice--------"+countprice);
		countpriceN = parseFloat($("#total_number").html())+countPrice - dkFee;    alert("countpriceN--------"+countpriceN);
	}
	$("#total_number").html(countpriceN.toFixed(2));	
}

var crporName;
var crporTel;
var crporCity;
var crporAddress;
function sureToPay() {
	var body = "商品购买";
    var syScore = parseInt($("#integralInput").val());    //所用积分
    var openId = dataGet("openId");    
    var yzf = parseFloat($("#total_number").html());    //应支付
    var userUuid = dataGet("userUuid");     
    var crporRemarks = $("#store_remark").val();
    
    var jc_item = $('.div_storeInfo');
    var goodsInfo = '';
	for (var i = 0; i < jc_item.length; i++) {  //循环每一商品
		var item = jc_item.eq(i);
		var item_goodName = item.find('.img_store_pic').html();
		var item_goodPrice = item.find('.div_storeInfo_detail').find('.div_storeInfo_price').html();
		var item_goodCount = item.find('.div_storeInfo_detail').find('.count_number').find('.span_count_flag,.div_storeInfo_number').html();
		var item_goodScore = item.find('.div_storeInfo_detail').find('.div_count').find('.span_count_flag').html();
		
		if(goodsInfo==''){
			goodsInfo = item_goodName+'~'+item_goodPrice+'~'+item_goodCount+'~'+item_goodScore.split(":")[1];
		}else{
			goodsInfo = goodsInfo +"#"+item_goodName+'~'+item_goodPrice+'~'+item_goodCount+'~'+item_goodScore.split(":")[1];
		}
	}
    
	var crporMail = null;
    var data = "crporName="+crporName+"&crporTel="+crporTel+"&crporCity="+crporCity+"&crporAddress="+crporAddress+
    	"&crporMail="+crporMail +"&crporRemarks="+crporRemarks+"&userUuid="+userUuid+"&body="+body+"&openId="+openId +"&attach=2"+
    	"&totalFee="+yzf+"&dkFee="+dkFee+"&zfFee="+yzf+"&syScore="+syScore+"&goodsInfo="+goodsInfo;
    var url = urlfile + "pay/get/package/storeCart";
    ajaxTool("post",data,url,
        function error(XMLHttpRequest, textStatus, errorThrown,fnErr){
            alert("error:" + data);
        },
        function success(data){
            if(!data.success) {
                alert(data.errMsg);
            }else{
                goToPay(data);
            }
        }
    );
}

/**
 * 查看用户积分
 */
function viewsScore(userUuid){
    var data = "&crusrUuid="+userUuid;
    var url = urlfile + "coreUser/views/score";
    ajaxTool("post",data,url,
        function error(XMLHttpRequest, textStatus, errorThrown,fnErr){
            alert("error:" + data);
        },
        function success(data){
            if(!data.success) {
                alert(data.errMsg);
            }else{
                crusrPoints = data.data.crusrPoints;
                $('#crusrPoints').html('你有'+ crusrPoints +'积分');
                
                jfdkbl = data.data.jfdkbl;   
            }
        }
    );
}

//积分抵扣
var dkFeeN = 0;
function countIntegral() {
    var integralInput = parseInt($("#integralInput").val());   //用户输入的积分数
    if(integralInput > crusrPoints){
        integralInput = crusrPoints;
        $("#integralInput").val(integralInput);
    }
	//抵扣费用 = 用户输入的积分数*积分抵扣比例
    if(dkFee == 0){
    	dkFee = integralInput * jfdkbl;
    	dkFeeN = dkFee;
    	$('#span_integral').html("-" + dkFee.toFixed(2));
    }else{
    	dkFeeN = (integralInput * jfdkbl) - dkFee;
    	$('#span_integral').html("-" + (integralInput * jfdkbl).toFixed(2));
    }    

    var yzf = parseFloat($("#total_number").html());
    $('#total_number').html(parseFloat(yzf - dkFeeN).toFixed(2));
}
